package com.example.mybluetooth.ui.main;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProviders;

import com.example.mybluetooth.R;

/**
 * A placeholder fragment containing a simple view.
 * Placeholder是Fragment的子类，包含了一个简单的视图
 */
public class PlaceholderFragment extends Fragment {

    private static final String ARG_SECTION_NUMBER = "section_number";
//pageViewModel对象作为成员变量，是为了实现Fragment之间的信息共享，
    private PageViewModel pageViewModel;

    public static PlaceholderFragment newInstance(int index) {
//        实例化生成一个空对象
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ARG_SECTION_NUMBER, index);
//       绑定一个bundle对象，作为fragment实例化时构造函数使用的参数
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        使用pageViewModel保存当前对象
        pageViewModel = ViewModelProviders.of(this).get(PageViewModel.class);
        int index = 1;
        if (getArguments() != null) {
//      只要实例化完毕，则可以通过getArguments()方法获取，fragment对象中包含的参数bundle，并解析该值
            index = getArguments().getInt(ARG_SECTION_NUMBER);
        }
//   通过调用pageViewModel的自定义方法来传值
        pageViewModel.setIndex(index);
    }

    @Override
    public View onCreateView(
            @NonNull LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_main, container, false);
        final TextView textView = root.findViewById(R.id.section_label);
//       通过pageViewModel的getText().observe()获得该pageViewMode的观察着，随时更新该文本视图的内容
        pageViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
            @Override
            public void onChanged(@Nullable String s) {
                textView.setText(s);
            }
        });
        ImageView imageView = root.findViewById(R.id.image1);
        imageView.setImageResource(R.drawable.t011);
        return root;
    }
}